#!/usr/bin/python
# -*- coding: utf-8 -*-
# author: zhaofeng-shu33
# description: update student info from given csv files
import MySQLdb # from mysqlclient
import os
import argparse
import csv

import utility # user provided package

csv_header = []
csv_header_except_student_id = ['student_mentor_name']
def custom_select(cursor, dic):
    global csv_header_except_student_id
    student_id = '11' + dic['student_id']
    result = utility.select(cursor, student_id, csv_header_except_student_id)
    try:
        result[0]
    except Exception as e:
        student_id = '1' + student_id
        result = utility.select(cursor, student_id, csv_header_except_student_id)
    update_dic = {}
    for index, i in enumerate(result[0]):
        if(i is None or len(i) == 0):
            name = csv_header_except_student_id[index]
            update_dic[name] = dic[name]
    update_dic['student_id'] = student_id
    return update_dic
def update_from_file(cursor, file_name):
    global csv_header, csv_header_except_student_id
    f = open(args.csv_file)
    csv_reader = csv.reader(f, delimiter = '\t')
    updated_cnt = 0
    csv_header = csv_reader.__next__()
    for item in csv_header:
        if(item != 'student_id'):
            csv_header_except_student_id.append(item)
    for row in csv_reader:
        dic = {}
        for index, key in enumerate(csv_header):
            if(row[index] != ''): # do not allow update empty field
                dic[key] = row[index]      
        update_dic = custom_select(cursor, dic)
        if(len(update_dic.keys())>1):
            updated_cnt += len(update_dic.keys()) -1        
            utility.update(cursor, update_dic)
    print('%d item updated' % updated_cnt)            
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("csv_file", help = "input csv files, first line is field name, with tab as delimiter")
    args = parser.parse_args()    
    db = MySQLdb.connect(host ="localhost",user="root", db="student_utsz", passwd=os.getenv("PASSWORD"), charset="utf8")
    cursor = db.cursor()
    update_from_file(cursor, args.csv_file)
    db.commit()
